import React, { FC, ReactElement, useState, useEffect, useRef } from 'react'
import style from '../index.less'
import { Form, Input, Cascader, Button, Row, Col, DatePicker } from 'antd'
import UploadCom from '@/components/UploadCom'
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons'
import moment from 'moment'
import { getQueryAddress } from '@/services'
import commonStyle from '@/pages/publicStyle'
import { BaseAddressOption, FirstForm } from '../../index.d'
import { dataFormat2 } from '@/untils/dictionaries'

const { TextArea } = Input
const RangePicker: any = DatePicker.RangePicker
interface OptionsItem {
  value: string
  label: string
  isLeaf?: boolean
}

const BaseInfo: FC<IProps> = (props): ReactElement => {
  // 表单组件  基本信息
  const [form] = Form.useForm()
  const pictureRef = useRef({
    initImgSrc: Function,
  })
  const thumbnailPictureRef = useRef({
    initImgSrc: Function,
  })
  const [schedules, setSchedules] = useState([
    { scheduleName: '', scheduleDate: '' },
  ]) // 活动日程列表
  const [options, setOptions] = useState<OptionsItem[]>() // 级联选择框数据
  const [formData, setFormData] = useState<FirstForm>({
    // 表单数据
    activityName: '',
    activitySite: '',
    activityOrganizers: '',
    activityContent: '',
    startDate: '',
    endDate: '',
    provinceCode: '',
    cityCode: '',
    pictureUrl: '',
    pictureKey: '',
    thumbnailPictureKey: '',
    thumbnailPictureUrl: '',
  })
  // 修改日程名称
  const changeScheduleName = (
    val: React.ChangeEvent<HTMLInputElement>,
    index: number,
  ) => {
    setSchedules([
      ...schedules.map((schedule, sIndex) => {
        if (index === sIndex) {
          schedule.scheduleName = val.target.value
        }
        return schedule
      }),
    ])
  }
  // 修改日程日期
  const changeScheduleDate = (val: string, index: number) => {
    setSchedules([
      ...schedules.map((schedule, sIndex) => {
        if (index === sIndex) {
          schedule.scheduleDate = val ? val : ''
        }
        return schedule
      }),
    ])
  }
  // 修改活动日期
  const activityTimeChange = (dataString: string[]) => {
    let oldFormData = JSON.parse(JSON.stringify(formData))
    oldFormData.startDate = dataString[0]
    oldFormData.endDate = dataString[1]
    setFormData(oldFormData)
  }
  // 修改活动数据
  const FromDataChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
    nodeName: string,
  ) => {
    let oldFormData = JSON.parse(JSON.stringify(formData))
    oldFormData[nodeName] = e.target.value
    setFormData(oldFormData)
  }
  // 获取地区列表
  const getAreaList = () => {
    getQueryAddress({ addressLevel: 1 }).then(res => {
      if (res.code === 200) {
        setOptions(
          res.data.map((item: BaseAddressOption) => ({
            value: item.addressCode,
            label: item.addressName,
            isLeaf: false,
          })),
        )
      }
    })
  }
  // 选取地区时加载二级地区
  const loadData = (selectedOptions: BaseAddressOption[]) => {
    const targetOption = selectedOptions[selectedOptions.length - 1]
    targetOption.loading = true

    getQueryAddress({
      addressLevel: 2,
      parentId: selectedOptions[0].value,
    }).then(res => {
      if (res.code === 200) {
        targetOption.loading = false //关闭请求图标
        targetOption.children = res.data.map((item: any) => ({
          value: item.addressCode,
          label: item.addressName,
        }))
        // console.log('地区', targetOption, selectedOptions, options);

        setOptions([...options])
      }
    })
  }
  // 选取二级地区
  const cascaderChangeArea = (value: any[]) => {
    if (Array.isArray(value)) {
      let oldFormData = JSON.parse(JSON.stringify(formData))
      oldFormData.provinceCode = value[0]
      oldFormData.cityCode = value[1]
      setFormData(oldFormData)
    }
  }
  // 活动图图片上传
  const imgAUploadSuccess = (imgData: any) => {
    let oldFormData = JSON.parse(JSON.stringify(formData))
    oldFormData.pictureUrl = imgData.imgUrl
    oldFormData.pictureKey = imgData.imgKey
    setFormData(oldFormData)
  }
  // 缩略图图片上传
  const imgBUploadSuccess = (imgData: any) => {
    let oldFormData = JSON.parse(JSON.stringify(formData))
    oldFormData.thumbnailPictureUrl = imgData.imgUrl
    oldFormData.thumbnailPictureKey = imgData.imgKey
    setFormData(oldFormData)
  }
  // 活动图校验
  const pictureUpACheck = (rules: any, value: any, callback: any) => {
    try {
      if (!formData.pictureUrl) {
        return Promise.reject('请提交上传活动图')
      } else {
        return Promise.resolve()
      }
    } catch (error) {
      callback(error)
    }
  }
  // 缩略图校验
  const pictureUpBCheck = (rules: any, value: any, callback: any) => {
    try {
      if (!formData.thumbnailPictureUrl) {
        return Promise.reject('请提交上传活动图')
      } else {
        return Promise.resolve()
      }
    } catch (error) {
      callback(error)
    }
  }
  // 下一步
  const goforNext = () => {
    form.validateFields().then(nameList => {
      props.goForNext(
        {
          ...formData,
          scheduleVOS: schedules.filter(
            item => item.scheduleName || item.scheduleDate,
          ),
        },
        1,
      )
    })
  }
  // 保存草稿
  const saveMust = () => {
    props.saveDrafts()
  }
  useEffect(() => {
    getAreaList()
    console.log(props.defaultFormData)
    let getData = JSON.parse(JSON.stringify(props.defaultFormData))
    form.setFieldsValue({
      activityName: getData.activityName,
      Area: [getData.provinceCode, getData.cityCode],
      activityTime: [
        getData.startDate ? moment(getData.startDate, dataFormat2) : undefined,
        getData.endDate ? moment(getData.endDate, dataFormat2) : undefined,
      ],
      activitySite: getData.activitySite,
      activityOrganizers: getData.activityOrganizers,
      activityContent: getData.activityContent,
      pictureUrl: getData.pictureUrl,
      thumbnailPictureUrl: getData.thumbnailPictureUrl,
    })
    if (pictureRef.current) {
      pictureRef.current.initImgSrc(getData.pictureUrl)
    }
    if (thumbnailPictureRef.current) {
      thumbnailPictureRef.current.initImgSrc(getData.thumbnailPictureUrl)
    }
    if (getData.scheduleVOS && getData.scheduleVOS.length > 0) {
      setSchedules(getData.scheduleVOS)
      delete getData.scheduleVOS
    }
    setFormData(getData)
  }, [props.defaultFormData])
  const { detailCardBox, detailFormTitle } = style
  const { mt20, mt10, mt50, mr10, completeW } = commonStyle
  return (
    <div className={detailCardBox} style={mt20}>
      <div className={detailFormTitle} style={mt20}>
        请填写活动的基本信息
      </div>
      <Form {...layout} form={form} name="control-hooks" style={mt20}>
        <Row>
          <Col span={12}>
            <Form.Item
              name="activityName"
              label="活动名称"
              rules={[{ required: true, message: '请输入活动名称' }]}
            >
              <Input
                placeholder="请输入活动名称"
                onChange={e => {
                  FromDataChange(e, 'activityName')
                }}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="Area"
              label="地区选择"
              rules={[{ required: true, message: '请选择活动开办地区' }]}
            >
              <Cascader
                options={options}
                loadData={loadData}
                onChange={cascaderChangeArea}
                changeOnSelect
                placeholder="请选择活动地点"
              />
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <Form.Item
              name="activityTime"
              label="活动时间"
              rules={[{ required: true, message: '请选择活动时间' }]}
            >
              <RangePicker
                style={completeW}
                format={dataFormat2}
                onChange={(dates: moment.Moment[], datestrings: string[]) => {
                  activityTimeChange(datestrings)
                }}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="activitySite"
              label="活动地点"
              rules={[{ required: true, message: '请输入活动地点' }]}
            >
              <Input
                placeholder="请输入活动地点"
                onChange={e => {
                  FromDataChange(e, 'activitySite')
                }}
              />
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <Form.Item
              name="activityOrganizers"
              label="活动主办方"
              rules={[{ required: true, message: '请输入活动主办方' }]}
            >
              <Input
                placeholder="请输入活动主办方"
                onChange={e => {
                  FromDataChange(e, 'activityOrganizers')
                }}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="activityContent"
              label="活动内容"
              rules={[{ required: true, message: '请输入活动内容' }]}
            >
              <TextArea
                rows={2}
                placeholder="请输入活动内容"
                value={formData.activityContent}
                onChange={e => {
                  FromDataChange(e, 'activityContent')
                }}
              />
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={12}>
            <Form.Item
              name="pictureUrl"
              label="活动图"
              rules={[{ required: true, validator: pictureUpACheck }]}
            >
              <UploadCom
                tagMessage="推荐尺寸: 1035*261"
                UploadSuccess={imgAUploadSuccess}
                isImgBtn={true}
                ref={pictureRef}
              ></UploadCom>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="thumbnailPictureUrl"
              label="缩略图"
              rules={[{ required: true, validator: pictureUpBCheck }]}
              {...tailLayout}
            >
              <UploadCom
                tagMessage="推荐尺寸: 168*216"
                UploadSuccess={imgBUploadSuccess}
                isImgBtn={true}
                ref={thumbnailPictureRef}
              ></UploadCom>
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <div className={detailFormTitle} style={mt20}>
        请编写活动日程规划
        <span style={initStyle.subtitleSize}>（可添加多条）</span>
      </div>
      <Row style={mt20}>日程名称</Row>
      {schedules.map((item, index) => (
        <Row style={mt10} key={index}>
          <Col span={8}>
            <Input
              value={item.scheduleName}
              placeholder="请输入活动名称"
              onChange={val => {
                changeScheduleName(val, index)
              }}
            />
          </Col>
          <Col
            span={4}
            style={{
              margin: '0 5px',
            }}
          >
            <DatePicker
              value={
                item.scheduleDate
                  ? moment(item.scheduleDate, dataFormat2)
                  : undefined
              }
              format={dataFormat2}
              style={completeW}
              onChange={(val: any, valString: string) => {
                changeScheduleDate(valString, index)
              }}
            />
          </Col>
          <Col
            span={1}
            style={{
              lineHeight: '32px',
              color: '#eb2f96',
            }}
          >
            <DeleteOutlined
              style={{ cursor: 'pointer' }}
              onClick={() => {
                setSchedules(
                  schedules.filter((sItem, sIndex) => index !== sIndex),
                )
              }}
            />
          </Col>
        </Row>
      ))}
      <Row style={mt20}>
        <Col span={8}>
          <Button
            style={completeW}
            type="dashed"
            icon={<PlusOutlined />}
            onClick={() => {
              setSchedules([
                ...schedules,
                { scheduleName: '', scheduleDate: '' },
              ])
            }}
          >
            添加
          </Button>
        </Col>
      </Row>
      <Row style={mt50}>
        <Button onClick={saveMust}>保存草稿</Button>
        <Button style={mr10}>预览</Button>
        <Button type="primary" style={mr10} onClick={goforNext}>
          下一步
        </Button>
      </Row>
    </div>
  )
}

export default BaseInfo

const layout = {
  labelCol: { span: 24 },
  wrapperCol: { span: 16 },
}

const tailLayout = {
  wrapperCol: { offset: 0, span: 4 },
}

interface IProps {
  goForNext: Function
  defaultFormData: any
  saveDrafts: Function
}

const initStyle = {
  subtitleSize: {
    fontSize: '12px',
    color: '#b9b9b9',
  },
}
const failImg =
  ''
